package com.dh.offer;

import com.dh.leetcode.common.TreeNode;
import com.dh.leetcode.common.TreeNodeIterator;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @ClassName: _32_cong_shang_dao_xia_da_yin_er_cha_shu_lcof
 * @Description: 剑指 Offer 32 - I. 从上到下打印二叉树
 * <p>
 * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
 * <p>
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 * <p>
 * 3
 * / \
 * 9  20
 * /  \
 * 15   7
 * 返回：
 * <p>
 * [3,9,20,15,7]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 节点总数 <= 1000
 * <p>
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
 * @Author: shouzimu
 * @Date: 2020/12/10 15:45
 */
public class _32_cong_shang_dao_xia_da_yin_er_cha_shu_lcof {
    public int[] levelOrder(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        //按层遍历树,先放入队列
        if (null != root) {
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);

            while (!queue.isEmpty()) {
                int max = queue.size();
                for (int i = 0; i < max; i++) {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
            }
        }
        //复制数组方式超过99.73%速度  89.57%内存
        int[] array = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
        //lambda 方式超过26% 内存 51%
        //  return list.stream().mapToInt(t -> t).toArray();
    }

    @Test
    public void levelOrderTest() {
        TreeNode node = TreeNodeIterator.initTestTree(new Integer[]{3, 9, 20, null, null, 15, 7});
        Assert.assertArrayEquals(new int[]{3, 9, 20, 15, 7}, levelOrder(node));
        node = TreeNodeIterator.initTestTree(new Integer[]{});
        Assert.assertArrayEquals(new int[]{}, levelOrder(node));

    }
}
